home *** CD-ROM | disk | FTP | other *** search
- Path: news.ichange.com!newsmaster
- From: Jesse Liberty <jl@staff.ichange.com>
- Newsgroups: comp.lang.c++
- Subject: Re: Newbie Question on using function ptr or Casting?
- Date: Fri, 15 Mar 1996 14:07:59 -0500
- Organization: AT&T
- Message-ID: <3149C00F.1CFA@staff.ichange.com>
- References: <19960314170244.sstryker@sover.net>
- NNTP-Posting-Host: 140.244.99.60
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (Win95; I)
- CC: jl@staff.ichange.com
-
- Stew Stryker wrote:
- >... He has a base class which implements a linked list. One of its methods is
- > called get_next_record(), which returns the pointer to the next record...
- > In the derived class, which holds a list of employees, he's printing out
- > all the values in the list in a print() function
-
- > void employees::print() {
- >
- > employees *current = this;
- >
- > while (current) {
- > cout "Employee name: " << current->emp_name << "\n";
- >
- > current = (employees*)current->get_next_record();
- > }
- >
- > cout << "End of employee list.\n";
- > }
- >
- > My confusion is on the line that reads:
- >
- > current = (employees*)current->get_next_record();
- >
- > He says that he's casting the results of the linked_list get_next_record()
- > function from a void pointer (which is how this base class method is
- > defined) to a pointer of the employees type. In my reading of my only C++
- > manual (Teach Yourself C++ Programming in 21 Days, by Jesse Liberty), this
- > looks kinda like a function pointer. This book also refers briefly to
- > casting of data, and says it's generally a sign of a poor design.
- > ... void* get_next_record();
-
- Nope, not a function. The syntax
-
- current = (employees*)current->get_next_record();
-
- says to the compiler:
-
- "take current and cast it to be an employees pointer and then
- use that pointer to call get_next_record() assigning the result to
- current."
-
- Your buddy's code has get_next_record returning a void * which can point
- to anything but which must be cast to point to a particular type before
- it can be used. This is a c-programmer's solution to this type of list
- problem, but C++ offers a far better (type safe) alternative: templates.
-
-
- By the way, while it is true that I said that casting is often a sign of
- poor design, I was referring to casting down a pointer to a base object
- to its "real" derived type -- a different issue than we have here.
-
-
-
- --
- ------
- Jesse Liberty [AT&T New Media Services]
- jl@staff.ichange.com ZDNet: 72241,72
- Teach Yourself C++ In 21 Days. Sams 1994
- Teach Yourself MORE C++ In 21 Days. Sams 1996
- Teach Yourself ANSI C++ In 21 Days. Sams 1996
- C++: An Introduction To Programming. Que 1996
-